import sys
import random

from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWidgets import QApplication
from PyQt5 import uic
from PyQt5.QtWidgets import QMainWindow, QApplication
import serial.tools.list_ports

from DAO import dao
import binascii
import json


# from Local_app import Ui_MainWindow


# from UI import do_question_window
# from mysql import mysql

# class do_question(do_question_window, mysql):
class local_ui(QMainWindow, dao):
    def __init__(self):
        super(local_ui, self).__init__()
        # self.date_text_ascii = None
        # self.date_text = None
        # self.date_ascii = None
        self.LEDSwitch = None
        self.init_local_ui()
        self.get_serial_list()
        self.ser = serial.Serial(timeout=0.5)
        self.seria_lPort = None
        self.timer = QTimer(self)
        self.timer_value = 100
        self.ser.baudrate = self.L_select_baud.currentText()
        self.timer.timeout.connect(self.time_out)

    def init_local_ui(self):
        self.ui = uic.loadUi("./Local_app.ui")
        self.init_local_login_ui()
        self.init_local_status_ui()
        self.init_local_control_led_ui()
        self.init_windows_switch()

    def init_local_login_ui(self):
        self.L_select_serial = self.ui.L_serialSelect
        self.L_select_baud = self.ui.L_baudSelect

        self.L_open_button = self.ui.L_serialOn
        self.L_close_button = self.ui.L_serialOff

        self.L_open_button.setEnabled(True)
        self.L_close_button.setEnabled(False)

        self.L_select_serial.activated.connect(self.port_change)
        self.L_select_baud.activated.connect(self.baud_change)
        self.L_open_button.clicked.connect(self.connect_btn)
        self.L_close_button.clicked.connect(self.connect_exit_btn)
        # self.L_button_led_on.clicked.connect(self.connect_led_on)
        # self.L_button_led_off.clicked.connectFalse)
    def init_windows_switch(self):
        self.L_actionCloud = self.ui.L_actionCloud
        # self.L_actionLocate = self.ui.L_actionLocate

        self.L_actionCloud.triggered.connect(self.cloud_window)
        self.L_actionCloud.triggered.connect(self.ui.close)
        # self.L_actionLocate.clicked.connect(self.cloud_window)


    def init_local_status_ui(self):
        self.L_status_temperature = self.ui.L_Temperature
        self.L_status_humidity = self.ui.L_Humidity
        self.L_status_serial = self.ui.L_serialStatus
        self.L_status_led = self.ui.L_ledStatus
        self.L_led = self.ui.L_led

        self.L_status_temperature.setText('')
        self.L_status_humidity.setText('')
        self.L_status_serial.setText('否')
        self.L_status_led.setText('')
        self.L_led.setPixmap(QPixmap('./grey.png'))

    def init_local_control_led_ui(self):
        self.L_button_led_on = self.ui.L_ledOnButton
        self.L_button_led_off = self.ui.L_ledOffButton

        self.L_button_led_on.setEnabled(False)
        self.L_button_led_off.setEnabled(False)

        self.L_button_led_on.clicked.connect(self.connect_led_on)
        self.L_button_led_off.clicked.connect(self.connect_led_off)

    def connect_led_on(self):
        # text = 'params_LEDSwitch_ON'
        text = '1'
        self.ser_send = text
        self.ser.write(self.ser_send.encode('utf8'))
        # print(self.ser_send)
        # self.ser_send = self.send_text.toPlainText() + '\n'
        # #
        #         self.ser.write(self.ser_send.encode('gb2312'))
        #         print('发送数据：' + self.ser_send)

    def connect_led_off(self):
        # text = 'params_LEDSwitch_OFF'
        text = '0'
        self.ser_send = text
        self.ser.write(self.ser_send.encode('utf8'))
        # print(self.ser_send)

    def get_serial_list(self):
        self.L_select_serial.addItems(self.get_com_list_function()[0])
        self.serial_port = self.get_com_list_function()[1]

    def connect_btn(self):
        if self.com_list != []:
            if self.serial_port != None:
                if self.L_open_button.text() == '打开':
                    self.ser.port = self.serial_port
                    print(self.ser.port)
                    print(self.ser.baudrate)
                    self.ser.open()
                    self.timer.start(self.timer_value)
                    self.L_open_button.setEnabled(False)
                    self.L_close_button.setEnabled(True)
                    self.L_button_led_on.setEnabled(True)
                    self.L_button_led_off.setEnabled(True)
                    # self.connectButton.setText('关闭')
                    self.L_status_serial.setText('是')
                    print('串口已连接')
                    self.L_led.setPixmap(QPixmap('./green.png'))
                # else:
                #     # self.connectButton.setText('连接')
                #     self.ser.close()
                #     # self.timer.stop()
                #     # self.timer.stop()
                #     self.L_led.setPixmap(QPixmap('./red.png'))
            else:
                self.L_select_serial.clear()
                self.get_serial_list()
        else:
            self.serial_port = None
            self.L_select_serial.clear()

    def connect_exit_btn(self):
        # self.connectButton.setText('连接')
        self.ser.close()
        # self.timer.stop()
        self.L_status_serial.setText('否')
        self.timer.stop()
        self.L_open_button.setEnabled(True)
        self.L_close_button.setEnabled(False)
        self.L_led.setPixmap(QPixmap('./red.png'))

    def port_change(self, text):
        self.serial_port = text

    def baud_change(self, text):
        self.baud = text
        self.ser.baudrate = self.L_select_baud.currentText()

    # def send_btn(self):
    #     # if self.connectButton.text() == '关闭' and self.serial_port != []:
    #     if self.L_status_serial.text() == '关闭' and self.serial_port != []:
    #         self.ser_send = self.send_text.toPlainText() + '\n'
    # #
    #         self.ser.write(self.ser_send.encode('gb2312'))
    #         print('发送数据：' + self.ser_send)
    #     else:
    #         print('请先打开串口')
    #
    def time_out(self):
        try:
            self.date_ascii = self.ser.read_all()
            self.date_text = str(binascii.b2a_hex(self.date_ascii))[2:-1]
            self.date_text_ascii = self.date_ascii.decode('gb2312')

            if self.date_text_ascii is not '':
                # print(type(self.date_text_ascii))
                # print(self.date_text_ascii)

                # self.date_text_ascii = self.date_text_ascii.replace('"', "")
                text = eval(self.date_text_ascii)
                print(text)

                CurrentHumidity = text['params']['CurrentHumidity']['value']
                CurrentTemperature = text['params']['CurrentTemperature']['value']
                LEDSwitch = text['params']['LEDSwitch']['value']
                print(LEDSwitch)
                self.L_status_temperature.setText(str(CurrentTemperature))
                self.L_status_humidity.setText(str(CurrentHumidity))
                if LEDSwitch == 1:
                    self.L_status_led.setText('开')
                else:
                    self.L_status_led.setText('关')
                # print(self.date_text)
                # self.receive_text.append(self.date_text_ascii)
            else:
                pass
            self.timer.start(self.timer_value)
        except Exception:
            pass

    def local_window(self):
        self.w1 = local_ui()
        # self.w1.ui.setWindowIcon(QIcon("./yss.ico"))
        self.w1.setWindowTitle("本地串口控制")
        self.w1.ui.show()


    def cloud_window(self):
        from CLOUD_UI import cloud_ui
        self.w2 = cloud_ui()
        # self.w2.ui.setWindowIcon(QIcon("./yss.ico"))
        self.w2.setWindowTitle("云端远程控制")
        self.w2.ui.show()
if __name__ == "__main__":
    app = QApplication(sys.argv)
    a = local_ui()
    a.ui.setWindowTitle("串口控制")
    a.ui.show()
    app.exec()
